package com.pay.demo.squirrel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.squirrelframework.foundation.fsm.annotation.StateMachineParameters;
import org.squirrelframework.foundation.fsm.annotation.Transit;
import org.squirrelframework.foundation.fsm.annotation.Transitions;
import org.squirrelframework.foundation.fsm.impl.AbstractUntypedStateMachine;

/**
 * @program: demo
 * @description:
 * @author: guoxh
 * @create: 2019-04-03 11:30
 **/
@Slf4j
@StateMachineParameters(stateType = State.class, eventType = Trigger.class,
        //StateMachineContext 自定义上下文，用来传递数据
        contextType = DiscountRefundStateMachineContext.class)
@Transitions({
        @Transit(from = "PENDING", to = "CONFIRMING", on = "APPLY_CONFIRM", callMethod = "doSomething"),//确认申请事件
        @Transit(from = "CONFIRMING", to = "REJECTED", on = "REJECT"),//驳回审核事件
        @Transit(from = "CONFIRMING", to = "REFUND_APPROVING", on = "APPLY_APPROVED"),//通过审核事件
        @Transit(from = "REFUND_APPROVING", to = "REFUND_APPROVED", on = "REFUND_APPROVED"),//退款审核通过-发起退款事件
        @Transit(from = "REFUND_APPROVED", to = "REFUND_FINISHED", on = "REFUND_FINISH_CONFIRM")//完成退款事件
})
public class DiscountRefundStateMachine extends AbstractUntypedStateMachine {
    protected ApplicationContext applicationContext;

    //定义构造函数接受ApplicationContext注入([参看New State Machine Instance](http://hekailiang.github.io/squirrel/))
    public DiscountRefundStateMachine(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void doSomething(State fromState, State toState, Trigger event, DiscountRefundStateMachineContext context) {
        log.info("do something, fromState:{},toState:{}", fromState, toState);
    }

    @Override
    protected void afterTransitionCompleted(Object fromState, Object toState, Object event, Object context) {
        if (context instanceof DiscountRefundStateMachineContext && toState instanceof State) {
            //从上下文中获取需要持久化的数据，例如订单ID等
            DiscountRefundStateMachineContext discountRefundStateMachineContext = (DiscountRefundStateMachineContext) context;
            Long orderId = discountRefundStateMachineContext.currentInstanceId();
            Long val = discountRefundStateMachineContext.currentInstance(orderId);
            log.info("持久化:{}", val);
        } else {
            try {
                throw new Exception("type not support, context expect " + DiscountRefundStateMachineContext.class.getSimpleName() + ", actually "
                        + context.getClass().getSimpleName() + ", state expect " + State.class.getSimpleName()
                        + ", actually "
                        + toState.getClass().getSimpleName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
